package com.yincheng.oes.business.service.impl.ycyk;

import com.alibaba.fastjson.JSON;
import com.yincheng.oes.business.model.dto.TPStudentDailyTaskDTO;
import com.yincheng.oes.business.service.StudentDailyTaskQueryApi;
import com.yincheng.oes.business.util.HttpUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author yangsiyong
 * @version 1.0
 * @description: query student daily task info from ycyk
 * @date 2022/3/6 9:49 AM
 */
@Component
public class StudentDailyTaskManagerFromYcyk implements StudentDailyTaskQueryApi {
    /**
     * 日志
     */
    private static final Logger LOGGER = LogManager.getLogger(StudentDailyTaskManagerFromYcyk.class);

    private static final String URL_YCYK = "https://oa.ycyk.cn/api/daily_punch_in_record";

    private static final String UTF8 = "utf8";

    private static final String PARAM_KEY = "m";

    private static final String YYYYMMDD = "yyyy/M/d";

    private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat(YYYYMMDD);

    private static final SimpleDateFormat YYYY_MM_DD = new SimpleDateFormat("yyyyMMdd");

    @Override
    public TPStudentDailyTaskDTO queryStudentDailyTask(String account) {
        if (StringUtils.isEmpty(account)) {
            LOGGER.error("when query daily task from ycyk, the account is null!");
            return null;
        }
        return queryStudentDailyTaskByPunchDate(account, new Date());
    }

    @Override
    public List<TPStudentDailyTaskDTO> batchQueryStudentDailyTasks(String account) {
        if (StringUtils.isEmpty(account)) {
            LOGGER.error("when query daily task from ycyk, the account is null!");
            return null;
        }
        Map<String, String> params = new HashMap<>();
        params.put(PARAM_KEY, account);
        try {
            String responseStr = HttpUtil.get(URL_YCYK, params, UTF8);
            if (StringUtils.isEmpty(responseStr)) {
                return null;
            }
            StudentTaskFromYcyk studentTaskFromYcyk = JSON.parseObject(responseStr, StudentTaskFromYcyk.class);
            if (Objects.isNull(studentTaskFromYcyk) || CollectionUtils.isEmpty(studentTaskFromYcyk.getTask())) {
                return null;
            }
            return getStudentDailyTasks(studentTaskFromYcyk);
        } catch (Exception e) {
            LOGGER.error("query daily task from ycyk error", e);
            return null;
        }
    }

    private List<TPStudentDailyTaskDTO> getStudentDailyTasks(StudentTaskFromYcyk studentTaskFromYcyk) {
        return studentTaskFromYcyk.getTask().stream().filter(Objects::nonNull)
                .map(this::getTpStudentDailyTaskDTO).collect(Collectors.toList());
    }

    private TPStudentDailyTaskDTO getTpStudentDailyTaskDTO(DailyTaskFromYcyk task) {
        TPStudentDailyTaskDTO dailyTask = new TPStudentDailyTaskDTO();
        dailyTask.setDailyTaskTotalNum(task.getDailyTaskTotalNum());
        dailyTask.setTaskDate(task.getTaskDate());
        dailyTask.setDailyTaskCorrectNum(task.getDailyTaskCorrectNum());
        dailyTask.setLiveBroadcastState(task.getLiveBroadcastState());
        dailyTask.setRecordedBroadcastCompletedCount(task.getRecordedBroadcastCompletedCount());
        dailyTask.setRecordedBroadcastTotalCount(task.getRecordedBroadcastTotalCount());
        try {
            Date parse = SIMPLE_DATE_FORMAT.parse(task.getTaskDate());
            String format = YYYY_MM_DD.format(parse);
            dailyTask.setTaskDateIntValue(Integer.valueOf(format));
        } catch (ParseException e) {
            LOGGER.error("parse taskDate {} error", task.getTaskDate(), e);
        }
        return dailyTask;
    }

    @Override
    public TPStudentDailyTaskDTO queryStudentDailyTaskByPunchDate(String account, Date date) {
        if (StringUtils.isEmpty(account)) {
            LOGGER.error("when query daily task from ycyk, the account is null!");
            return null;
        }
        if (Objects.isNull(date)) {
            LOGGER.error("when query daily task from ycyk, the date is null!");
            return null;
        }
        Map<String, String> params = new HashMap<>();
        params.put(PARAM_KEY, account);
        try {
            String responseStr = HttpUtil.get(URL_YCYK, params, UTF8);
            if (StringUtils.isEmpty(responseStr)) {
                return null;
            }
            StudentTaskFromYcyk studentTaskFromYcyk = JSON.parseObject(responseStr, StudentTaskFromYcyk.class);
            if (Objects.isNull(studentTaskFromYcyk) || CollectionUtils.isEmpty(studentTaskFromYcyk.getTask())) {
                return null;
            }
            return getStudentDailyTask(studentTaskFromYcyk, date);
        } catch (IOException e) {
            LOGGER.error("query daily task from ycyk error", e);
            return null;
        }
    }

    private TPStudentDailyTaskDTO getStudentDailyTask(StudentTaskFromYcyk studentTaskFromYcyk, Date date) {
        String format = SIMPLE_DATE_FORMAT.format(date);
        Map<String, TPStudentDailyTaskDTO> map = new HashMap<>();
        studentTaskFromYcyk.getTask().stream().filter(Objects::nonNull).forEach(task -> {
            TPStudentDailyTaskDTO dailyTask = getTpStudentDailyTaskDTO(task);
            map.put(task.getTaskDate(), dailyTask);
        });
        // todo update to local cache, local mysql
        return map.get(format);
    }
}
